package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.*;
import cn.itcast.domain.company.Company;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;

    @RequestMapping(value = "/list",name = "展示购销合同货物列表数据")
    public String findAll(String contractId,@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer pageSize){

//        1、当前合同的所有货物数据
//        2、用来生产货物的工厂数据
//        3、购销合同的id

//        查询购销合同货物 应该有什么条件 contractId
        ContractProductExample example = new ContractProductExample();
        example.createCriteria().andContractIdEqualTo(contractId);
        PageInfo<ContractProduct> pageInfo = contractProductService.findAll(example,page,pageSize);
//        1、当前合同的所有货物数据
        request.setAttribute("page",pageInfo); //这个 “page” 不能写错，因为页面就是取的是page中的值

        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
//        2、用来生产货物的工厂数据
        request.setAttribute("factoryList",factoryList);

//        3、购销合同的id
        request.setAttribute("contractId",contractId);

        return "cargo/product/product-list";
    }


    @RequestMapping(value = "/toAdd",name = "进入到添加购销合同页面")
    public String toAdd(){
        return "cargo/contract/contract-add";
    }

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping(value = "/edit",name = "保存购销合同货物方法")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto ){
        String imageUrl = null;
        try {
            imageUrl = fileUploadUtil.upload(productPhoto);
        } catch (Exception e) {
            imageUrl=null;
            e.printStackTrace();
        }
        contractProduct.setProductImage(imageUrl);

        if(StringUtils.isEmpty(contractProduct.getId())){
            contractProduct.setId(UUID.randomUUID().toString());
            contractProduct.setCompanyId(getCompanyId());
            contractProduct.setCompanyName(getCompanyName());
            contractProductService.save(contractProduct);
        }else{
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
    }

    @RequestMapping(value = "/toUpdate",name = "进入到修改购销合同货物页面")
    public String toUpdate(String id){
//        需要回显的数据有：
//        1、当前的货物数据  2、用来生产货物的工厂数据 3

        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);


        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
//        2、用来生产货物的工厂数据
        request.setAttribute("factoryList",factoryList);
        return "cargo/product/product-update";
    }


    @RequestMapping(value = "/delete",name = "删除购销合同货物方法")
    public String delete(String id,String contractId){
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }


    @RequestMapping(value = "/toImport",name = "进入到导入货物页面")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }

    @RequestMapping(value = "/import",name = "进入到导入货物页面")
    public String importXlsx(String contractId,MultipartFile file) throws Exception{

        //        1、创建一个工作薄，有内容的工作薄
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
//        2、获取工作薄中的第一个工作表
        Sheet sheet = workbook.getSheetAt(0);
//        3、获取工作表中指定的行
        int lastRowIndex = sheet.getLastRowNum(); //最后一行的索引值
        Row row = null;
        ContractProduct product = null;
        List<ContractProduct> productList = new ArrayList<>();
        for (int i = 1; i <= lastRowIndex; i++) {
            product = new ContractProduct();
            row = sheet.getRow(i);
//            生产厂家	货号	数量	包装单位(PCS/SETS)	装率	箱数	单价	货物描述	要求

            String factoryName = row.getCell(1).getStringCellValue(); //生产厂家
            product.setFactoryName(factoryName);

            String productNo = row.getCell(2).getStringCellValue(); //货号
            product.setProductNo(productNo);

            Integer cnumber = ((Double)row.getCell(3).getNumericCellValue()).intValue(); //数量
            product.setCnumber(cnumber);

            String packingUnit = row.getCell(4).getStringCellValue(); //包装单位(PCS/SETS)
            product.setPackingUnit(packingUnit);

            String loadingRate = ((Double)row.getCell(5).getNumericCellValue()).toString(); //装率 string
            product.setLoadingRate(loadingRate);

            Integer boxNum = ((Double)row.getCell(6).getNumericCellValue()).intValue(); //箱数 Integer
            product.setBoxNum(boxNum);

            Double price = row.getCell(7).getNumericCellValue(); //单价 double
            product.setPrice(price);

//            还需要添加默认的数据 id、所属的合同ID 、企业id 、企业名称
            product.setId(UUID.randomUUID().toString());
            product.setCompanyId(getCompanyId());
            product.setCompanyName(getCompanyName());
            product.setContractId(contractId);

            productList.add(product);

        }
        contractProductService.saveList(productList); //好处1、可以保证数据一致性  2、节省了事务的开启了关闭次数




        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }


}
